import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { fieldApi } from '@/api/fieldApi'

/**
 * 字段管理相关的组合式函数
 * @returns {Object} 字段管理相关的方法和状态
 */
export function useFields() {
  // 可用字段列表
  const availableFields = ref([])
  const certNumberField = ref(null)
  const maxSelectable = ref(11)

  /**
   * 获取可用字段
   */
  const fetchAvailableFields = async () => {
    try {
      // 获取所有字段，设置较大的limit值
      const res = await fieldApi.getFields({ limit: 1000 })
      if (res.code === 200) {
        const fields = res.data.items
        // 分离证书编号字段
        certNumberField.value = fields.find(f => f.field_name === 'cert_number')
        availableFields.value = fields
      } else {
        console.error('获取字段失败:', res.message)
        ElMessage.error('获取字段列表失败')
        availableFields.value = []
      }
    } catch (error) {
      console.error('获取字段出错:', error)
      ElMessage.error('获取字段列表失败')
      availableFields.value = []
    }
  }

  /**
   * 获取字段名称
   */
  const getFieldName = fieldName => {
    if (fieldName === 'cert_number' && certNumberField.value) {
      return certNumberField.value.name
    }
    const field = availableFields.value.find(f => f.field_name === fieldName)
    return field ? field.name : '未知字段'
  }

  /**
   * 处理字段选择
   */
  const handleFieldSelect = (cert, field) => {
    // 证书编号字段不允许选择
    if (field.field_name === 'cert_number') return

    if (!cert.selectedFields) {
      cert.selectedFields = []
    }
    
    if (field.selected) {
      cert.selectedFields.push(field)
    } else {
      cert.selectedFields = cert.selectedFields.filter(f => f.field_name !== field.field_name)
    }
  }

  /**
   * 批量删除字段
   */
  const handleBatchDelete = (cert) => {
    if (!cert.selectedFields?.length) return
    
    // 过滤掉证书编号字段，确保它不会被删除
    const fieldsToDelete = cert.selectedFields.filter(field => field.field_name !== 'cert_number')
    
    if (fieldsToDelete.length === 0) {
      ElMessage.warning('没有可删除的字段')
      return
    }

    ElMessageBox.confirm(
      `确定删除选中的 ${fieldsToDelete.length} 个字段吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      // 过滤掉选中的字段，但保留证书编号字段
      cert.fields = cert.fields.filter(field => 
        field.field_name === 'cert_number' || !fieldsToDelete.some(selected => selected.field_name === field.field_name)
      )
      cert.selectedFields = []
    })
  }

  /**
   * 添加字段
   */
  const addFields = async (cert, fieldNames) => {
    // 过滤掉证书编号字段，不允许重复添加
    const validFieldNames = fieldNames.filter(name => name !== 'cert_number')
    
    if (!validFieldNames.length) {
      ElMessage.warning('请选择至少一个有效字段')
      return false
    }

    // 检查字段数量限制（包含证书编号在内最多12个）
    if (cert.fields.length + validFieldNames.length > 12) {
      ElMessage.warning('最多只能添加12个字段（包含证书编号）')
      return false
    }
    
    // 添加新字段
    validFieldNames.forEach(fieldName => {
      // 检查是否已存在
      if (cert.fields.some(f => f.field_name === fieldName)) {
        return
      }
      
      const fieldInfo = availableFields.value.find(f => f.field_name === fieldName)
      if (fieldInfo) {
        cert.fields.push({
          field_name: fieldName,
          name: fieldInfo.name,
          description: '',
          selected: false
        })
      }
    })

    return true
  }

  /**
   * 获取可选字段列表
   */
  const getAvailableFields = (index) => {
    // 第一个字段固定为证书编号
    if (index === 1) {
      return certNumberField.value ? [certNumberField.value] : []
    }
    // 其他字段不能选择证书编号
    return availableFields.value.filter(f => f.field_name !== 'cert_number')
  }

  /**
   * 获取添加字段对话框的可选字段列表
   */
  const getDialogAvailableFields = (cert) => {
    if (!cert) return []
    
    // 只过滤掉证书编号字段，显示所有其他字段
    return availableFields.value.filter(field => 
      field.field_name !== 'cert_number'
    )
  }

  onMounted(() => {
    fetchAvailableFields()
  })

  return {
    availableFields,
    certNumberField,
    maxSelectable,
    getFieldName,
    handleFieldSelect,
    handleBatchDelete,
    addFields,
    getAvailableFields,
    getDialogAvailableFields,
    fetchAvailableFields
  }
} 